/**
 * 安全管理JavaScript
 * 提供安全管理功能，包括实时威胁监控、IP封锁管理和限流配置
 */
class SecurityManager {
    constructor() {
        this.token = this.getQueryParam('token');
        this.apiBase = '/api/security';
        this.currentEventPage = 1;
        this.currentEventPageSize = 20;
        this.eventFilters = {};
        this.blockIPData = null;
        this.unblockIPData = null;
        
        this.init();
    }
    
    init() {
        this.bindEvents();
        this.loadSecurityDashboard();
        this.loadSecurityEvents();
        this.loadBlockedIPs();
        this.loadRateLimits();
        
        // 启动实时监控
        this.startRealTimeMonitoring();
    }
    
    bindEvents() {
        // IP封锁表单提交
        document.getElementById('block-ip-form').addEventListener('submit', (e) => {
            e.preventDefault();
            this.handleBlockIP();
        });
        
        // 筛选器变化
        document.getElementById('event-type-filter').addEventListener('change', () => {
            this.eventFilters.event_type = document.getElementById('event-type-filter').value;
            this.currentEventPage = 1;
            this.loadSecurityEvents();
        });
        
        document.getElementById('threat-level-filter').addEventListener('change', () => {
            this.eventFilters.threat_level = document.getElementById('threat-level-filter').value;
            this.currentEventPage = 1;
            this.loadSecurityEvents();
        });
    }
    
    getQueryParam(param) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(param);
    }
    
    // API请求方法
    async apiRequest(endpoint, options = {}) {
        const defaultOptions = {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${this.token}`
            }
        };
        
        const config = { ...defaultOptions, ...options };
        
        try {
            const response = await fetch(`${this.apiBase}${endpoint}`, config);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            return await response.json();
        } catch (error) {
            console.error('API请求失败:', error);
            this.showNotification('请求失败: ' + error.message, 'error');
            throw error;
        }
    }
    
    // 加载安全仪表板
    async loadSecurityDashboard() {
        try {
            const response = await this.apiRequest('/dashboard');
            const data = response.data;
            
            // 更新统计数据
            document.getElementById('today-events').textContent = 
                data.statistics.failed_login_attempts + data.statistics.suspicious_requests;
            document.getElementById('blocked-ips').textContent = data.statistics.blocked_ips;
            document.getElementById('failed-logins').textContent = data.statistics.failed_login_attempts;
            
        } catch (error) {
            console.error('加载安全仪表板失败:', error);
        }
    }
    
    // 加载安全事件
    async loadSecurityEvents() {
        try {
            const params = new URLSearchParams({
                page: this.currentEventPage,
                page_size: this.currentEventPageSize,
                ...this.eventFilters
            });
            
            const response = await this.apiRequest(`/events?${params}`);
            const data = response.data;
            
            this.renderSecurityEvents(data.events);
            this.renderSecurityEventsPagination(data);
            
        } catch (error) {
            console.error('加载安全事件失败:', error);
            this.renderSecurityEvents([]);
        }
    }
    
    // 渲染安全事件
    renderSecurityEvents(events) {
        const tbody = document.getElementById('security-events-tbody');
        
        if (events.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="7" class="px-6 py-4 text-center text-gray-500">
                        暂无安全事件
                    </td>
                </tr>
            `;
            return;
        }
        
        tbody.innerHTML = events.map(event => `
            <tr class="hover:bg-gray-50">
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    ${new Date(event.timestamp).toLocaleString()}
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <span class="px-2 py-1 text-xs font-medium rounded-full ${this.getEventTypeClass(event.event_type)}">
                        ${this.getEventTypeLabel(event.event_type)}
                    </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    ${event.username || '匿名用户'}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    ${event.ip_address}
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    ${event.endpoint}
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                    <span class="px-2 py-1 text-xs font-medium rounded-full ${this.getThreatLevelClass(event.threat_level)}">
                        ${this.getThreatLevelLabel(event.threat_level)}
                    </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <button onclick="securityManager.showEventDetails('${event.id}')" 
                            class="text-blue-600 hover:text-blue-900">
                        查看详情
                    </button>
                </td>
            </tr>
        `).join('');
    }
    
    // 渲染安全事件分页
    renderSecurityEventsPagination(data) {
        const pagination = document.getElementById('security-events-pagination');
        
        if (data.total_pages <= 1) {
            pagination.innerHTML = '';
            return;
        }
        
        let html = '<div class="flex space-x-2">';
        
        // 上一页
        if (data.page > 1) {
            html += `
                <button onclick="securityManager.goToPage(${data.page - 1})" 
                        class="px-3 py-2 bg-white border rounded-md hover:bg-gray-50">
                    上一页
                </button>
            `;
        }
        
        // 页码
        for (let i = Math.max(1, data.page - 2); i <= Math.min(data.total_pages, data.page + 2); i++) {
            const activeClass = i === data.page ? 'bg-blue-500 text-white' : 'bg-white hover:bg-gray-50';
            html += `
                <button onclick="securityManager.goToPage(${i})" 
                        class="px-3 py-2 border rounded-md ${activeClass}">
                    ${i}
                </button>
            `;
        }
        
        // 下一页
        if (data.page < data.total_pages) {
            html += `
                <button onclick="securityManager.goToPage(${data.page + 1})" 
                        class="px-3 py-2 bg-white border rounded-md hover:bg-gray-50">
                    下一页
                </button>
            `;
        }
        
        html += '</div>';
        pagination.innerHTML = html;
    }
    
    // 加载封锁IP列表
    async loadBlockedIPs() {
        try {
            const response = await this.apiRequest('/blocked-ips');
            const data = response.data;
            
            this.renderBlockedIPs(data.blocked_ips);
            
        } catch (error) {
            console.error('加载封锁IP列表失败:', error);
            this.renderBlockedIPs([]);
        }
    }
    
    // 渲染封锁IP列表
    renderBlockedIPs(ips) {
        const container = document.getElementById('blocked-ips-list');
        
        if (ips.length === 0) {
            container.innerHTML = `
                <div class="text-center text-gray-500 py-8">
                    <i class="fas fa-check-circle text-4xl mb-4 text-green-500"></i>
                    <p>暂无被封锁的IP地址</p>
                </div>
            `;
            return;
        }
        
        container.innerHTML = ips.map(ip => `
            <div class="flex items-center justify-between p-3 bg-gray-50 rounded-md">
                <div class="flex items-center space-x-3">
                    <div class="bg-red-100 p-2 rounded-full">
                        <i class="fas fa-ban text-red-600"></i>
                    </div>
                    <div>
                        <p class="font-medium text-gray-900">${ip}</p>
                        <p class="text-sm text-gray-500">已封锁</p>
                    </div>
                </div>
                <button onclick="securityManager.showUnblockIPConfirm('${ip}')" 
                        class="text-green-600 hover:text-green-800">
                    <i class="fas fa-unlock"></i>
                </button>
            </div>
        `).join('');
    }
    
    // 加载限流配置
    async loadRateLimits() {
        try {
            const response = await this.apiRequest('/rate-limits');
            const data = response.data;
            
            this.renderRateLimits(data.limits);
            
        } catch (error) {
            console.error('加载限流配置失败:', error);
            this.renderRateLimits({});
        }
    }
    
    // 渲染限流配置
    renderRateLimits(limits) {
        const container = document.getElementById('rate-limits-config');
        
        const limitTypes = [
            { key: 'default', name: '默认限制', icon: 'fa-globe', color: 'blue' },
            { key: 'auth', name: '认证端点', icon: 'fa-key', color: 'orange' },
            { key: 'upload', name: '文件上传', icon: 'fa-upload', color: 'purple' },
            { key: 'api', name: 'API端点', icon: 'fa-code', color: 'green' },
            { key: 'strict', name: '严格限制', icon: 'fa-shield-alt', color: 'red' }
        ];
        
        container.innerHTML = limitTypes.map(type => {
            const limit = limits[type.key] || { requests: 0, window: 0 };
            return `
                <div class="bg-gray-50 p-4 rounded-md">
                    <div class="flex items-center space-x-3 mb-3">
                        <div class="bg-${type.color}-100 p-2 rounded-full">
                            <i class="fas ${type.icon} text-${type.color}-600"></i>
                        </div>
                        <h3 class="font-medium text-gray-900">${type.name}</h3>
                    </div>
                    <div class="space-y-2">
                        <div class="flex justify-between">
                            <span class="text-sm text-gray-600">请求数量:</span>
                            <span class="font-medium">${limit.requests}</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-sm text-gray-600">时间窗口:</span>
                            <span class="font-medium">${limit.window}秒</span>
                        </div>
                        <div class="flex justify-between">
                            <span class="text-sm text-gray-600">速率:</span>
                            <span class="font-medium">${(limit.requests / limit.window * 60).toFixed(1)}/分钟</span>
                        </div>
                    </div>
                    <button onclick="securityManager.editRateLimit('${type.key}')" 
                            class="mt-3 w-full bg-${type.color}-500 text-white py-2 rounded-md hover:bg-${type.color}-600">
                        编辑配置
                    </button>
                </div>
            `;
        }).join('');
    }
    
    // 处理IP封锁
    async handleBlockIP() {
        const formData = {
            ip_address: document.getElementById('block-ip-address').value,
            reason: document.getElementById('block-ip-reason').value,
            duration_hours: parseInt(document.getElementById('block-ip-duration').value),
            notes: document.getElementById('block-ip-notes').value
        };
        
        this.showBlockIPConfirmModal(formData);
    }
    
    // 显示IP封锁确认模态框
    showBlockIPConfirmModal(data) {
        this.blockIPData = data;
        const modal = document.getElementById('block-ip-confirm-modal');
        const message = document.getElementById('block-ip-confirm-message');
        
        message.textContent = `确定要封锁IP地址 ${data.ip_address} 吗？封锁时长：${data.duration_hours}小时`;
        modal.classList.remove('hidden');
        modal.classList.add('flex');
    }
    
    // 隐藏IP封锁确认模态框
    hideBlockIPConfirmModal() {
        const modal = document.getElementById('block-ip-confirm-modal');
        modal.classList.add('hidden');
        modal.classList.remove('flex');
        this.blockIPData = null;
    }
    
    // 确认封锁IP
    async confirmBlockIP() {
        if (!this.blockIPData) return;
        
        try {
            await this.apiRequest('/block-ip', {
                method: 'POST',
                body: JSON.stringify(this.blockIPData)
            });
            
            this.showNotification('IP地址封锁成功', 'success');
            this.hideBlockIPConfirmModal();
            this.loadBlockedIPs();
            this.loadSecurityDashboard();
            
            // 清空表单
            document.getElementById('block-ip-form').reset();
            
        } catch (error) {
            console.error('封锁IP失败:', error);
            this.showNotification('封锁IP失败: ' + error.message, 'error');
        }
    }
    
    // 显示解除封锁确认模态框
    showUnblockIPConfirm(ip) {
        this.unblockIPData = { ip_address: ip };
        const modal = document.getElementById('unblock-ip-confirm-modal');
        const message = document.getElementById('unblock-ip-confirm-message');
        
        message.textContent = `确定要解除封锁IP地址 ${ip} 吗？`;
        modal.classList.remove('hidden');
        modal.classList.add('flex');
    }
    
    // 隐藏解除封锁确认模态框
    hideUnblockIPConfirmModal() {
        const modal = document.getElementById('unblock-ip-confirm-modal');
        modal.classList.add('hidden');
        modal.classList.remove('flex');
        this.unblockIPData = null;
    }
    
    // 确认解除封锁
    async confirmUnblockIP() {
        if (!this.unblockIPData) return;
        
        try {
            await this.apiRequest(`/block-ip/${this.unblockIPData.ip_address}`, {
                method: 'DELETE'
            });
            
            this.showNotification('IP地址解除封锁成功', 'success');
            this.hideUnblockIPConfirmModal();
            this.loadBlockedIPs();
            this.loadSecurityDashboard();
            
        } catch (error) {
            console.error('解除封锁失败:', error);
            this.showNotification('解除封锁失败: ' + error.message, 'error');
        }
    }
    
    // 刷新威胁监控
    async refreshThreatMonitor() {
        try {
            const response = await this.apiRequest('/dashboard');
            const data = response.data;
            
            this.renderThreatMonitor(data);
            
        } catch (error) {
            console.error('刷新威胁监控失败:', error);
        }
    }
    
    // 渲染威胁监控
    renderThreatMonitor(data) {
        const container = document.getElementById('threat-monitor');
        
        const metrics = data.real_time_metrics;
        
        container.innerHTML = `
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                <div class="bg-blue-50 p-4 rounded-md">
                    <div class="flex items-center space-x-3">
                        <div class="bg-blue-100 p-2 rounded-full">
                            <i class="fas fa-exclamation-triangle text-blue-600"></i>
                        </div>
                        <div>
                            <p class="text-sm text-gray-600">活跃威胁</p>
                            <p class="text-2xl font-bold text-blue-600">${metrics.active_threats}</p>
                        </div>
                    </div>
                </div>
                
                <div class="bg-red-50 p-4 rounded-md">
                    <div class="flex items-center space-x-3">
                        <div class="bg-red-100 p-2 rounded-full">
                            <i class="fas fa-ban text-red-600"></i>
                        </div>
                        <div>
                            <p class="text-sm text-gray-600">今日封锁IP</p>
                            <p class="text-2xl font-bold text-red-600">${metrics.blocked_ips_today}</p>
                        </div>
                    </div>
                </div>
                
                <div class="bg-orange-50 p-4 rounded-md">
                    <div class="flex items-center space-x-3">
                        <div class="bg-orange-100 p-2 rounded-full">
                            <i class="fas fa-user-times text-orange-600"></i>
                        </div>
                        <div>
                            <p class="text-sm text-gray-600">今日失败登录</p>
                            <p class="text-2xl font-bold text-orange-600">${metrics.failed_logins_today}</p>
                        </div>
                    </div>
                </div>
                
                <div class="bg-purple-50 p-4 rounded-md">
                    <div class="flex items-center space-x-3">
                        <div class="bg-purple-100 p-2 rounded-full">
                            <i class="fas fa-eye-slash text-purple-600"></i>
                        </div>
                        <div>
                            <p class="text-sm text-gray-600">可疑请求</p>
                            <p class="text-2xl font-bold text-purple-600">${metrics.suspicious_requests_today}</p>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="mt-4 p-4 bg-gray-50 rounded-md">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-600">系统状态</p>
                        <p class="text-lg font-medium ${data.system_status === 'secure' ? 'text-green-600' : 'text-red-600'}">
                            ${data.system_status === 'secure' ? '安全' : '警告'}
                        </p>
                    </div>
                    <div class="text-sm text-gray-500">
                        最后更新: ${new Date(data.last_updated).toLocaleString()}
                    </div>
                </div>
            </div>
        `;
    }
    
    // 启动实时监控
    startRealTimeMonitoring() {
        // 每30秒刷新一次威胁监控
        setInterval(() => {
            this.refreshThreatMonitor();
            this.loadSecurityDashboard();
        }, 30000);
        
        // 每60秒刷新一次安全事件
        setInterval(() => {
            this.loadSecurityEvents();
        }, 60000);
    }
    
    // 页面跳转
    goToPage(page) {
        this.currentEventPage = page;
        this.loadSecurityEvents();
    }
    
    // 编辑限流配置
    editRateLimit(type) {
        // 这里可以实现编辑限流配置的功能
        this.showNotification('编辑限流配置功能开发中', 'info');
    }
    
    // 显示事件详情
    showEventDetails(eventId) {
        // 这里可以实现显示事件详情的功能
        this.showNotification('事件详情功能开发中', 'info');
    }
    
    // 工具方法
    getEventTypeClass(type) {
        const classes = {
            'login_success': 'bg-green-100 text-green-800',
            'login_failure': 'bg-red-100 text-red-800',
            'api_access': 'bg-blue-100 text-blue-800',
            'suspicious_request': 'bg-yellow-100 text-yellow-800',
            'rate_limit_exceeded': 'bg-orange-100 text-orange-800'
        };
        return classes[type] || 'bg-gray-100 text-gray-800';
    }
    
    getEventTypeLabel(type) {
        const labels = {
            'login_success': '登录成功',
            'login_failure': '登录失败',
            'api_access': 'API访问',
            'suspicious_request': '可疑请求',
            'rate_limit_exceeded': '限流触发'
        };
        return labels[type] || type;
    }
    
    getThreatLevelClass(level) {
        const classes = {
            'low': 'bg-green-100 text-green-800',
            'medium': 'bg-yellow-100 text-yellow-800',
            'high': 'bg-orange-100 text-orange-800',
            'critical': 'bg-red-100 text-red-800'
        };
        return classes[level] || 'bg-gray-100 text-gray-800';
    }
    
    getThreatLevelLabel(level) {
        const labels = {
            'low': '低',
            'medium': '中',
            'high': '高',
            'critical': '严重'
        };
        return labels[level] || level;
    }
    
    // 显示通知
    showNotification(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `fixed top-4 right-4 px-6 py-3 rounded-md shadow-lg z-50 ${this.getNotificationClass(type)}`;
        notification.textContent = message;
        
        document.body.appendChild(notification);
        
        // 3秒后自动移除
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }
    
    getNotificationClass(type) {
        const classes = {
            'success': 'bg-green-500 text-white',
            'error': 'bg-red-500 text-white',
            'warning': 'bg-yellow-500 text-white',
            'info': 'bg-blue-500 text-white'
        };
        return classes[type] || classes['info'];
    }
    
    // 公共方法
    async refreshBlockedIPs() {
        await this.loadBlockedIPs();
    }
    
    async refreshRateLimits() {
        await this.loadRateLimits();
    }
    
    async filterSecurityEvents() {
        this.currentEventPage = 1;
        await this.loadSecurityEvents();
    }
}

// 全局实例
let securityManager;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    securityManager = new SecurityManager();
});

// 模态框控制
function hideBlockIPConfirmModal() {
    securityManager.hideBlockIPConfirmModal();
}

function confirmBlockIP() {
    securityManager.confirmBlockIP();
}

function hideUnblockIPConfirmModal() {
    securityManager.hideUnblockIPConfirmModal();
}

function confirmUnblockIP() {
    securityManager.confirmUnblockIP();
}

function refreshThreatMonitor() {
    securityManager.refreshThreatMonitor();
}